<template>
	<a-modal :visible="visible" width="800px" :title="`授权设置`" centered destroyOnClose :maskClosable="false" @cancel="cancel" :footer="null" :bodyStyle="{padding: 0}">
		<div class="flex-container-nomal" style="height: 70vh">
			<div class="flex1 auto-y">
				<div class="flex-container-nomal">
					<template v-if="detail.showAccessLock">
						<template v-if="detail.hasAccess">
							<div class="access-authorization-module">
								<div class="d-module-title" style="margin-top: 0">
									<b>门禁授权</b>
									<span v-if="!detail.accessOnline" class="error-color">(门禁离线，待门禁在线后同步授权)</span>
								</div>
								<vxe-table :data="detail.renterInfos" border size="mini" show-overflow :row-config="{isHover: true}">
									<vxe-column title="人员类型" :width="150">
										<template #default="{row}">
											{{ row.customerType == 1 ? (detail?.sourceType === 2 ? '入住人' : '承租人') : '同住人' }}
										</template>
									</vxe-column>
									<vxe-column field="name" title="姓名" :width="150"></vxe-column>
									<vxe-column title="门禁授权" align="center">
										<template #default="{row}">
											<a-checkbox-group v-model:value="row.accessAuthType">
												<a-checkbox :value="2">人脸</a-checkbox>
												<a-checkbox :value="3">手机开门</a-checkbox>
											</a-checkbox-group>
										</template>
									</vxe-column>
								</vxe-table>
							</div>
						</template>
						<template v-if="detail.hasLock && !lockTextShow">
							<div class="access-authorization-module">
								<div class="d-module-title">
									<b>门锁授权</b>
									<span v-if="sendOfflinePassword" class="error-color">(仅可发放离线密码，离线密码最长一年有效期)</span>
								</div>
								<vxe-table :data="detail.renterInfos" v-if="lockDecision.length" border size="mini" show-overflow :row-config="{isHover: true}">
									<vxe-column title="人员类型" :width="150">
										<template #default="{row}">
											{{detail?.sourceType === 2 ? '入住人' : row.customerType == 1 ? '承租人': '同住人'}}
										</template>
									</vxe-column>
									<vxe-column field="name" title="姓名" :width="150"></vxe-column>
									<vxe-column title="门锁授权" align="center">
										<template #default="{row}">
											<a-checkbox-group v-model:value="row.lockAuthType">
												<a-row>
													<a-col :span="8">
														<a-checkbox :value="1" v-if="lockDecision.includes(1)">密码</a-checkbox>
														<!-- 待调接口 -->
														<a-checkbox :value="4" v-if="lockDecision.includes(3)">蓝牙</a-checkbox>
													</a-col>
												</a-row>
											</a-checkbox-group>
										</template>
									</vxe-column>
								</vxe-table>
							</div>
						</template>
						<template v-if="lockTextShow && !lockDecision.includes(1) && !lockDecision.includes(3)">
							<div class="access-authorization-module">
								<div class="d-module-title">
									<b>门锁授权</b>
								</div>
								<div class="text-class">已关闭密码授权，如需开启请至设置-决策设置-安全设置中更改授权设置</div>
							</div>
						</template>
					</template>

					<template v-if="detail.showWaterEle">
						<!-- 电表 -->
						<div class="access-authorization-module" v-if="isLockinEnv() && hydropower && bindHydropower.bindEleMater">
							<div class="d-module-title" style="margin-top: 0">
								<b>电表</b>
								<span v-if="baseNumbe.eleMaterStatusName == '离线'" class="error-color">(设备已离线，请及时恢复在线)</span>
							</div>
							<vxe-table :data="electricityData" size="mini" show-overflow :row-config="{isHover: true}">
								<vxe-column title="剩余电量" field="remain"></vxe-column>
								<vxe-column title="是否清零" align="center">
									<template #default="{row}">
										<a-radio-group v-model:value="row.isClear">
											<a-radio :value="true">是</a-radio>
											<a-radio :value="false">否</a-radio>
										</a-radio-group>
									</template>
								</vxe-column>
							</vxe-table>
						</div>
						<!-- 水表 -->
						<div class="access-authorization-module" v-if="hydropower && (bindHydropower.bindClodWaterMater || bindHydropower.bindHotWaterMater)">
							<div class="d-module-title" style="margin-top: 0">
								<b>水表</b>
								<span v-if="[baseNumbe.clodWaterMaterStatusName, baseNumbe.hotWaterMaterStatusName].includes('离线')" class="error-color">(设备已离线，请及时恢复在线)</span>
							</div>
							<vxe-table :data="waterVolumeData" size="mini" show-overflow :row-config="{isHover: true}">
								<vxe-column title="剩余水费" field="remain"></vxe-column>
								<vxe-column title="是否清零" align="center">
									<template #default="{row}">
										<a-radio-group v-model:value="row.isClear">
											<a-radio :value="true">是</a-radio>
											<a-radio :value="false">否</a-radio>
										</a-radio-group>
									</template>
								</vxe-column>
							</vxe-table>
						</div>
					</template>
				</div>
			</div>
			<div class="a-modal-dialog-footer">
				<a-button type="primary" :loading="loading" :disabled="loading" @click="submit">确定</a-button>
			</div>
		</div>
	</a-modal>
</template>
<script setup lang="ts">
	import {ref, toRef, watch, reactive, computed} from 'vue'
	import {message} from 'ant-design-vue'
	import {RenterContractDevice} from '@/interface/contract'
	import {batchDeviceSave, eleMeterResetByCollector, getCurEleAndWaterQuantity, waterMeterChargeReset} from '@/api/contract'
	import {isD3B, isNBLock} from '@/utils/device'
	import {isLockinEnv} from 'yuxin-base/src/utils'
	import settingApi from 'yuxin-base/src/api/setting-api'

	const props = defineProps<{
		visible: boolean
		deviceDetail: RenterContractDevice
		//是否展示水电表 true展示
		hydropower: boolean
		isResubmit?:boolean
	}>()

	const detail = toRef(props, 'deviceDetail')

	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		bindHydropower.bindEleMater = false
		bindHydropower.bindClodWaterMater = false
		bindHydropower.bindHotWaterMater = false
		emit('success')
		emit('update:visible', false)
	}
	// 剩余电量
	const electricityData = ref<any>([])
	// 剩余水费
	const waterVolumeData = ref<any>([])
	//是否绑定水电设备
	const bindHydropower = reactive<any>({
		bindClodWaterMater: false,
		bindHotWaterMater: false,
		bindEleMater: false
	})

	const sendOfflinePassword = computed(() => {
		const {lockOnline, sn, pids} = detail.value
		// 蓝牙锁发离线
		if (sn && isD3B(sn)) return true
		// NB锁发在线
		if (sn && isNBLock(sn)) return false
		// 无网关发离线
		if (!pids) return true
		// 有网关看状态
		return !lockOnline
	})
	const loading = ref(false)
	const submit = () => {
		let renterDeviceInfoForms: any = []
		const params: any = {
			contractId: detail.value.id,
			houseId: detail.value.houseId,
			isResubmit:props?.isResubmit || false
		}
		if (detail.value.hasAccess) {
			detail.value.renterInfos.forEach((item: any) => {
				item.accessAuthType.forEach((authType: any) => {
					renterDeviceInfoForms.push({
						type: 1,
						renterType: item.customerType,
						renterId: item.id,
						renterName: item.name,
						authType
					})
				})
			})
		}
		if (detail.value.hasLock) {
			detail.value.renterInfos.forEach((item: any) => {
				item.lockAuthType.forEach((authType: any) => {
					renterDeviceInfoForms.push({
						type: 2,
						renterType: item.customerType,
						renterId: item.id,
						renterName: item.name,
						authType
					})
				})
			})
		}
		params.renterDeviceInfoForms = renterDeviceInfoForms
		if ((bindHydropower.bindHotClodMater || bindHydropower.bindHotWaterMater) && waterVolumeData.value[0].isClear) {
			setWaterMeterChargeReset()
		}
		if (bindHydropower.bindEleMater && electricityData.value[0].isClear) {
			setEleMeterResetByCollector()
		}
		if (renterDeviceInfoForms.length) {
			loading.value = true
			if(detail.value?.sourceType===2){
				params.grantTiming = 2
			}else if(params.hasOwnProperty('grantTiming')){
				delete params.grantTiming
			}

			batchDeviceSave(params)
				.then((res: any) => {
					message.success('操作成功')
					emit('success')
					cancel()
				})
				.finally(() => {
					loading.value = false
				})
		} else {
			cancel()
		}
	}

	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				getDecision()
				if (props.hydropower) {
					setEleAndWaterQuantity()
				}
			} else {
				electricityData.value = []
				waterVolumeData.value = []
				baseNumbe.value = {}
			}
		}
	)

	// 获取设备决策配置
	const lockDecision = ref<any>([])
	const lockTextShow = ref<boolean>(false)
	const getDecision = () => {
		settingApi
			.getDecisionList({
				bizPoint: 'SAFETY_SETTING',
				module: 'SAFETY'
			})
			.then(({data}) => {
				lockDecision.value = JSON.parse(data[data.findIndex((item: any) => item.mark === 'SAFETY_LOCK_SETTING')].value) || []
				// todo 门锁决策，1代表密码授权，授权暂时仅支持密码，没有密码不显示门锁授权
				if (detail.value.hasLock && !lockDecision.value.includes(1) && !lockDecision.value.includes(3)) {
					detail.value.hasLock = false
					lockTextShow.value = true
					// message.warning('')
				}else{
					lockTextShow.value = false
				}
			})
	}

	const baseNumbe = ref<any>({})
	const setEleAndWaterQuantity = () => {
		// 获取水电表详情
		getCurEleAndWaterQuantity({
			roomId: detail.value.houseId
		}).then((res: any) => {
			if (res.data.billGenerateMethod === 3) {
				return
			}
			bindHydropower.bindEleMater = res.data.bindEleMater
			bindHydropower.bindClodWaterMater = res.data.bindClodWaterMater
			bindHydropower.bindHotWaterMater = res.data.bindHotWaterMater
			electricityData.value = [
				{
					remain: (res.data.remainEleQuantity || 0) + '度',
					isClear: true
				}
			]
			waterVolumeData.value = [
				{
					remain: (res.data.remainWaterAmount || 0) + '元',
					isClear: true
				}
			]
			console.log(electricityData.value, waterVolumeData.value, '水电费')
			baseNumbe.value = res.data
		})
	}

	// 水费清零
	const setWaterMeterChargeReset = () => {
		waterMeterChargeReset({
			roomId: detail.value.houseId,
			source: '合同',
			contractId: detail.value.id
		}).then((res: any) => {})
	}
	// 电量清零
	const setEleMeterResetByCollector = () => {
		eleMeterResetByCollector({
			roomId: detail.value.houseId,
			source: '合同',
			contractId: detail.value.id
		}).then((res: any) => {})
	}
</script>
<style lang="less">
	.access-authorization-module {
		margin-top: 20px;
		&:first-child {
			margin-top: 0;
		}
		.text-class {
			color: red;
			margin-top: 0;
		}
	}
</style>
